package gqz.avdemo.player;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceView;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Description
 *
 * @author gqz
 * @date 2020/12/21
 */
public class Codec {
   private final String TAG = "Codec-->";
   private Surface surface;
   private MediaCodec mediaCodec;

   int width = 1080, height = 1920, frameRate = 15, i_rate = 5;

   public Codec(Surface surface) {
      this.surface = surface;
      try {
         mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
         MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC,
                 width, height);
         format.setInteger(MediaFormat.KEY_BIT_RATE, width * height/10);
         format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
         format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, i_rate);
         mediaCodec.configure(format, surface, null, 0);
         mediaCodec.start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   public void startDecode(byte[] data) {
      Log.v(TAG, "startDecode: 接收到数据：" + data.length);
      if (mediaCodec != null) {
         int bufIndex = mediaCodec.dequeueInputBuffer(100000);
         if (bufIndex >= 0) {
            ByteBuffer buf = mediaCodec.getInputBuffer(bufIndex);
            buf.clear();
            buf.put(data);
            mediaCodec.queueInputBuffer(bufIndex, 0, data.length, System.currentTimeMillis(), 0);
         }
         MediaCodec.BufferInfo bufInfo = new MediaCodec.BufferInfo();
         int outbufIndex = mediaCodec.dequeueOutputBuffer(bufInfo, 100000);
         //传入一帧编码数据可能会解析出多份原始数据
         while (outbufIndex >= 0) {
            mediaCodec.releaseOutputBuffer(outbufIndex, true);
            outbufIndex = mediaCodec.dequeueOutputBuffer(bufInfo, 0);
         }
      }
   }

   public void onDestroy() {
      mediaCodec.release();
      mediaCodec.stop();
   }
}
